// src/views/install/EnvCheck.tsx
import { useEffect, useState } from "react";
import { Button, Card, List, Spin } from "antd";
import { CheckCircleOutlined, CloseCircleOutlined } from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";

interface EnvStatus {
  name: string;
  command: string;
  status: "loading" | "ok" | "error";
  version?: string;
}

const EnvCheck = () => {
  const [envs, setEnvs] = useState<EnvStatus[]>([
    { name: "Git", command: "git --version", status: "loading" },
    { name: "Go", command: "go version", status: "loading" },
  ]);
  const [loading, setLoading] = useState(false);

  // 执行命令检测环境
  const checkEnv = async () => {
    setLoading(true);
    const newEnvs = [...envs];

    for (let i = 0; i < newEnvs.length; i++) {
      try {
        const version: string = await invoke("exec_command", { cmd: newEnvs[i].command });
        newEnvs[i].status = "ok";
        newEnvs[i].version = version.trim();
      } catch (err) {
        newEnvs[i].status = "error";
      }
    }

    setEnvs(newEnvs);
    setLoading(false);
  };

  useEffect(() => {
    checkEnv();
  }, []);

  return (
    <Card title="环境检测">
      <List
        itemLayout="horizontal"
        dataSource={envs}
        renderItem={(item) => (
          <List.Item>
            <List.Item.Meta
              title={item.name}
              description={item.version ? `版本: ${item.version}` : ""}
            />
            {item.status === "loading" && <Spin />}
            {item.status === "ok" && <CheckCircleOutlined style={{ color: "green" }} />}
            {item.status === "error" && <CloseCircleOutlined style={{ color: "red" }} />}
          </List.Item>
        )}
      />
      <Button type="primary" onClick={checkEnv} style={{ marginTop: 16 }} loading={loading}>
        重新检测
      </Button>
    </Card>
  );
};

export default EnvCheck;
